<?php if (isset($success_message)) : ?>
    <div class="noty_bar noty_theme_default noty_layout_topCenter noty_success" id="noty_success_1355937644582" style="cursor: pointer; left: 559.5px; display: block;">
        <div class="noty_message"><span class="noty_text">Guía creada con exito!</span></div>
    </div>
     
<?php endif; ?>
    <div class="noty_bar noty_theme_default noty_layout_topCenter noty_error" id="message_error_formAddPurchase" style="cursor: pointer; left: 559.5px;">
    <div class="noty_message"><span id="contentMessageErrorFormAddPurchase" class="noty_text">Debe agregar algún producto</span></div>
    </div>
<?php if (isset($success_message2)) : ?>
    <div class="noty_bar noty_theme_default noty_layout_topCenter noty_success" id="noty_success_1355937644582" style="cursor: pointer; left: 559.5px; display: block;">
        <div class="noty_message"><span class="noty_text">Guía actualizada con exito!</span></div>
    </div>
<?php endif; ?>



<script type="text/javascript">
    $(document).ready(function() {


<?php if (isset($searchsales)) {
    
} else {
    ?>
            $.ajax({
                'url': '<?php echo base_url(); ?>index.php/sales/codeguia',
                'success': function(res) {
                    $('input[name=numero]').val('');
                    $('input[name=numero]').val(res);
                    $('#numero').css('background', '#ffffff');

                }
            });
    //            $('li[id=type_document_chzn_o_1]').click(function() {
    //                $.ajax({
    //                    'url': 'index.php/sales/codeguia',
    //                    'success': function(res) {
    //                        $('input[name=numero]').val('');
    //                        $('input[name=numero]').val(res);
    //                        $('#numero').css('background', '#ffffff');
    //                    }
    //                });
    //
    //            })
    //            $('li[id=type_document_chzn_o_1]').click(function() {
    //                $.ajax({
    //                    'url': 'index.php/sales/codeguia',
    //                    'success': function(res) {
    //                        alert('boleta');
    //                        $('#numero').css('background', '#ffffff');
    //                    }
    //                });
    //
    //            })

            $('li[id=type_document_chzn_o_0]').click(function() {
                $.ajax({
                    'url': '<?php echo base_url(); ?>index.php/sales/codeguia',
                    'success': function(res) {
                        $('input[name=numero]').val('');
                        $('input[name=numero]').val(res);
                        $('#numero').css('background', '#ffffff');

                    }
                });

            })

<?php } ?>

        $('#noty_success_1355937644582').click(function() {
            $('#noty_success_1355937644582').fadeOut('fast');
        });

//        $('.c-Delete').live('click', function(){
//           $(this).remove();
//         });





    })
</script>
<div class="grid_container">

    <form id="formAddPurchase" action="<?php
    if (isset($searchsales)) {
        echo base_url() . 'index.php/sales/search';
    } else {
        echo base_url() . 'index.php/sales/submit';
    }
    ?> " method="post" class="form_container">
        <div class="grid_12">
            <div class="widget_wrap">
                <div class="widget_top">
                    <span class="h_icon magnifying_glass"></span>
                    <h6>
                    <?php if (isset($searchsales)) {
                    if (isset($datesale)) {
                       echo 'Editar Guía de Venta'; ?>                  
                    <?php }else
                    {
                        echo 'Buscar Guía de Venta'; ?>                  
                  <?php } ?>
                <?php } else {
                    echo 'Nueva Guía de Venta';?>                 
                <?php } ?>
                    </h6>
                </div>

                <div class="widget_content" style="margin-bottom: 30px">
                    <ul>
                        <li>
                            <div class="form_grid_12">
                                <div class="form_input">
                                    <div class=" form_grid_4 alpha">
                                        <label class="field_title">N° Documento</label>
                                      
                                     <input type="text" name="numero" id="numero" class="noEmpty" value="<?php
                                        if (isset($datesale)) {
                                            foreach ($datesale as $da) {
                                                echo $da->document_code;
                                            }
                                        }
                                        ?>" <?php
                                        if (isset($datesale)) {
                                             foreach ($datesale as $da) {
                                                if($da->document_code!=null)
                                                {
                                                     echo "";
                                                }
                                            }                                           
                                        }
                                        ?> tabindex="2">
                                    </div>
                                   <div class=" form_grid_4 alpha">

                                        <label class="field_title">Fecha</label>

                                        <input type="text" name="date"  id="date" value="<?php
                                        if (isset($datesale) && $contandodatos == 0) {
                                            foreach ($datesale as $da) {
                                                echo $da->date;
                                            }
                                        } else {
                                            if (isset($parametro))
                                            {
                                                echo "";
                                            }
                                            else
                                            {
                                                  echo date('d/m/Y');
                                            }
                                          
                                        }
                                        ?>" tabindex="3" <?php
                                        
                                       
                                         if(isset($datesale) && $contandodatos > 0){
                                             echo "";
                                         }else if(isset($datesale) && $contandodatos == 0){
                                             echo " readonly";
                                             
                                         }
                                           
                                        ?>>

                                    </div>
                                    <span class="clear"></span>
                                </div>
                            </div>
                        </li>
                        <li>
                            <div class="form_grid_12">
                                <div class="form_input">
                                    <div class="form_grid_5 alpha">
                                        <label class="field_title">Cliente</label>
                                        <?php
                                        $options = array();
                                        $options[0] = "";
                                        foreach ($clients as $td) {
                                            $options[$td->id] = $td->name;
                                        }

                                        $extra = 'id="client" tabindex="3" style="width:340px" class="chzn-select full" data-placeholder="Elegir..."';

                                        $buscando_cliente_de_guia = ''; /* variable que contendra el cliente de la guia buscada */
                                        if (isset($datesale)) {
                                            foreach ($datesale as $da) {
                                                $buscando_cliente_de_guia = $da->id_client;
                                            }
                                        }

                                        echo form_dropdown('client', $options, $buscando_cliente_de_guia, $extra);
                                        ?>

                                        <?php if (isset($searchsales)) {
                                            
                                        } else {
                                            ?>
                                            <a href="#" class="basic-modal">Nuevo</a>
                                        <?php } ?>
                                    </div>
                                    <div id="divRuc" class="form_grid_3" style="display: none">
                                        <label class="field_title">RUC</label>
                                    <?php
                                    $data = array(
                                        'id' => 'client_ruc',
                                        'name' => 'client_ruc',
                                        'tabindex' => '3',
                                        'class' => '',
                                        'readonly' => 'readonly'
                                    );
                                    echo form_input($data);
                                    ?>
                                    </div>
                                    <!-- div class="form_grid_4">
                                            <span class="field_title">DirecciÃ³n</span>
<?php
$data = array(
    'id' => 'client_address',
    'name' => 'client_address',
    'tabindex' => '4',
    'class' => '',
    'readonly' => 'readonly'
);
echo form_input($data);
?>
                                    </div-->
                                    <span class="clear"></span>
                                </div>
                            </div>
                        </li>
                        <li>
                           <div class="form_grid_12">
                                <div class="form_input">
                                    <div class="form_grid_8 alpha">
                                        <label class="field_title">Observaciones</label>
                                        <input type="text" name="observations" id="observations" tabindex="5" value="<?php
                    if (isset($datesale)) {
                        foreach ($datesale as $da) {
                            echo $da->observations;
                        }
                    } else {
                        
                    }
                    ?>">
                                    </div>
                                    <span class="clear"></span>
                                </div>
                            </div>
                        </li>
                    </ul>
<?php
if (isset($searchsales)) {
               
    if (isset($datesale)) {
        
        if(count($datesale)== 0)           
        {                       
        ?>
        <div class="noty_bar noty_theme_default noty_layout_topCenter noty_success" id="noty_success_1355937644583" style="cursor: pointer; left: 559.5px; display: block;">
        <div class="noty_message"><span class="noty_text">No se encontraron registros</span></div>
        </div>   
        <?
        }                   
        foreach ($datesale as $da) {
            $valor_guia = $da->id_sale;
                                     
            if ($valor_guia != "") {
                ?>
                                    <script>
                                        $(document).ready(function() {
                                            $('#addProduct').click(function(e) {
                                                $.ajax({
                                                    'url': url + '/sales/products/',
                                                    'type': 'POST',
                                                    'data': {
                                                        'code': '',
                                                        'description': ''
                                                    },
                                                    'success': function(res) {
                                                        $('#add-product-model').html(res);
                                                    }
                                                });
                                                $('#add-product-model').modal();
                                                return false;
                                            });

                                        })
                                    </script>

                                    <div class="form_grid_2 " style="margin-bottom: 10px; float: right">
                                        <button id="addProduct" class="btn_small btn_blue"><span>Agregar Producto</span></button>
                                    </div>
                                    
                <?php
       
            }
                 
        }
    }         
        else {
            
            ?>
                   <div class="form_grid_2" style="margin-bottom: 10px; float: right; margin-right: 0px;">
                        <button class="btn_small btn_blue"><span>Buscar</span></button>
                        </div>                  
            <?
    }
    ?>
                       



<?php } else { ?>

                        <script>
                            $(document).ready(function() {
                                $('#addProduct').click(function(e) {
                                    $.ajax({
                                        'url': url + '/sales/products/',
                                        'type': 'POST',
                                        'data': {
                                            'code': '',
                                            'description': ''
                                        },
                                        'success': function(res) {
                                            $('#add-product-model').html(res);
                                        }
                                    });
                                    $('#add-product-model').modal();
                                    return false;
                                });

                            })
                        </script>

                        <div class="form_grid_2 " style="margin-bottom: 10px; float: right">
                            <button id="addProduct" class="btn_small btn_blue"><span>Agregar Producto</span></button>
                        </div>

<?php 
}
?>


                    <table class="wtbl_list" border="1">
                        <thead>
                            <tr>
                                <th width="10%">Código</th>
                                <th width="30%">Descripción</th>
                                <th width="10%">Cajas</th>
                                <th width="10%">Empaques</th>
                                <th width="10%">Unidades</th>
                                <th width="20%">Precio</th>
                                <th width="20%">Subtotal</th>
                                <th width="10%"></th>
                            </tr>

                        </thead>

                        <tbody id="contentProductList">



<?php
if (isset($datesale)) {
    $contandoitem = 0;
   
    foreach ($saledetails as $sa) {                            
        $contandoitem++;       
        ?>
                                <script>
                                    $(document).ready(function() {

                                        

                                        $('.eliminar_<?php echo $contandoitem; ?>').click(function() {

                                            if (confirm('¿Desea eliminar este producto?')) {

                                                var subtotal_2 = $('input[name=subtotal_a<?php echo $contandoitem; ?>_]').val();
                                                var subtotalgeneral = $('input[name=subtotalgeneral]').val();
                                                var total = subtotalgeneral - subtotal_2;
                                                var totaldecimal = (total).toFixed(2);
                                                $('input[name=subtotalgeneral]').val(totaldecimal);


                                                var contandoitem = $('input[name=contandoitem]').val();



                                                $('input[name=contandoitem]').val(contandoitem - 1);

                                                $.ajax({
                                                    'url': url + '/sales/delete_detail',
                                                    'type': 'POST',
                                                    'data': {
                                                        'numero': $('input[name=numero]').val(),
                                                        'code': $('input[name=codigo_a<?php echo $contandoitem; ?>_]').val()
                                                    },
                                                    'success': function(res) {
                                                        if (res == 1) {

                                                            $.ajax({
                                                                'url': url + '/sales/edit_amout',
                                                                'type': 'POST',
                                                                'data': {
                                                                    'numero': $('input[name=numero]').val(),
                                                                    'amount': $('input[name=subtotalgeneral]').val()
                                                                },
                                                                'success': function(res) {

                                                                }
                                                            });
                                                        } else {
                                                            alert('No se pudo eliminar el producto.');
                                                        }
                                                    }
                                                });

                                                $('tr.fila_a<?php echo $contandoitem; ?>').remove();

                                            } else {

                                            }
                                        })


                                    })
                                </script>  
                                <tr class="fila_a<?php echo $contandoitem; ?>">
                                    <td>
                                        <input type="hidden" name="codigo_a<?php echo $contandoitem; ?>_" value="<?php echo $sa->code; ?>">
                                        <?php echo $sa->code; ?>
                                    </td>
                                    <td>
                                        <input type="hidden" name="description_a<?php echo $contandoitem; ?>_" value="<?php echo $sa->description; ?>">
                                <?php echo $sa->description; ?>
                                    </td>
                                    <td align="center">
                                        <input type="hidden" name="totalcaja_a<?php echo $contandoitem; ?>_" value="<?php echo $sa->box; ?>">
                                <?php echo $sa->box; ?></td>
                                    <td align="center">
                                        <input type="hidden" name="totalpaguete_a<?php echo $contandoitem; ?>_" value="<?php echo $sa->pack; ?>">
        <?php echo $sa->pack; ?></td>
                                    <td align="center"><input type="hidden" name="totalunidad_a<?php echo $contandoitem; ?>_" value="<?php echo $sa->unit; ?>">
        <?php echo $sa->unit; ?></td>
                                    <td align="center"><input type="hidden" name="precio_a<?php echo $contandoitem; ?>_" value="<?php echo $sa->price; ?>">
                            <?php echo $sa->price; ?></td>
                                    <td align="center"><input type="hidden" name="subtotal_a<?php echo $contandoitem; ?>_" value="<?php echo $sa->amount; ?>">
        <?php echo "s/." . $sa->amount; ?></td>
                                    <td><a href="#"  original-title="Eliminar" class="action-icons c-Delete eliminar_<?php echo $contandoitem; ?>">Delete</a></td>
                                </tr>
                        <?php
                        }
                    } else {
                        
                    }
                    ?>
                        </tbody>



                    </table>
                    <input type="hidden" name="contandoitem" value="<?php
                           if (isset($contandoitem)) {
                               echo $contandoitem;
                           }
                    ?>">

                    <input type="text" name="subtotalgeneral" id="subtotalgeneral" placeholder="0.00" value="<?php
                           if (isset($datesale)) {
                               foreach ($datesale as $da) {
                                   echo $da->amount;
                               }
                           } else {
                               echo "0.00";
                           }
                    ?>" readonly="true" style=" text-align:center; width: 100px; margin-right: 58px; float: right; background: #D0D0D0; font-family: arial; font-size: 15px; font-weight: bold;">
                    <input type="hidden" name="contenaumentador" id="contenaumentador" value="0">
                    <script type="text/javascript" >

                        /*var subtotal = 0;
                         function sumando(dato) {
                         var valor_catual =$('#subtotalgeneral').val();
                         //subtotal = parseFloat(valor_catual);
                         subtotal += dato;
                         subtotal_general_actual =  $('#subtotalgeneral').val(subtotal).toFixed(2);
                         parseFloat(subtotal_general_actual).toFixed(2);
                         }*/

                        function probar(numero) {
                             
                            $('tr.fila_' + numero + '').remove();
                            
                        }

                        $('button.c-Delete').live('click', function() {
                            if (confirm('¿Desea eliminar este producto?')) {
                            var a = $(this).val();
                            var valor_total_producto = $('input[name=subtotal_' + a + ']').val();
                            var valor_subtotal = $('input[name=subtotalgeneral]').val();

                            var subtotal_catual = (parseFloat(valor_subtotal) - parseFloat(valor_total_producto)).toFixed(2);

                            $('input[name=subtotalgeneral]').val(subtotal_catual);

                            subtotal = parseFloat(subtotal_catual);
                            
                            var contador_actual = $('#contenaumentador').val();
                            var contador_despues = contador_actual - 1;
                            contandoitem(contador_despues);
                            probar(a);                            
                            }
                            else
                                {
                                    
                                }
                        });


                        var contando = 0;

                        function contandoitem(dato) {
                            contando = dato;
                            $('#contenaumentador').val(contando);
                        }


                    </script>




                </div>
            </div>
            <br />
<?php if (!isset($parametro) == 1) : ?>
                <script type="text/javascript">
                    $(document).ready(function() {
                        
                        function checkCode() {

                            $.ajax({
                                'url': url + '/sales/search_code_unique/',
                                'type': 'POST',
                                'data': {'numero': $('input[name=numero]').val()},
                                'success': function(res) {
                                    //alert("alert res: " + res);
                                    if (res == 1) {

                                        alert('El código del documento ya fue ingresado anteriormente al sistema.');
                                        $('#numero').css('background', '#ff3333');

                                    } else if (res == 0) {


                                        $('#numero').css('background', '#ffffff');
                                        $('#formAddPurchase').submit();
                                    }
                                }
                            });

                        }

                        $('#numero').focus(function() {
                            $('#numero').css('background', '#ffffff');
                        })
                        $('input[name=date]').focus(function() {
                            $('input[name=date]').css('background', '#ffffff');
                        })


                        function formtrue() {
                            $('formAddPurchase').submit(function() {
                                return true;
                            });
                        }
                        function formfalse() {
                            $('formAddPurchase').submit(function() {
                                return false;
                            });
                        }

                        $('#guardar_guia').click(function() {
                            if ($('#contenaumentador').val() >= 1) {


                                //$('div[id=noty_success_1355937644582]').css('display', 'block');
                                $('div[id=message_error_formAddPurchase]').css('display', 'none');
                                if ($('input[name=numero]').val() !== '') {
                                    checkCode(); /*funcion ajax submit*/
                                } else {

                                    alert('Coloque codigo del documento');
                                }


                            } else {

                                $('div[id=noty_success_1355937644582]').css('display', 'none');
                                $('div[id=message_error_formAddPurchase]').css('display', 'block');

                                if ($('#numero').val() == '') {
                                    $('#numero').css('background', '#ff3333');
                                }

                                var fechaactual = new Date();


                                if ($('input[name=date]').val() == '') {
                                    $('input[name=date]').css('background', '#ff3333');
                                }





                            }

                        });
                                               
                    })
                </script>
                <?php
                if (isset($searchsales)) {
                    
                     if (isset($datesale)) {
                            foreach ($datesale as $da) {
                              $da->id_sale;
                 ?>
                <input type="hidden" name="id_sales" id="id_sales" value="<? echo $da->id_sale;?>">
                <?             
                ?>

                        <script>
                            $(document).ready(function() {
                                $('#Editar_guia_venta').click(function() {
                                    $('#formAddPurchase').attr('action', '<?php echo base_url(); ?>index.php/sales/submit');
                                    $('#formAddPurchase').submit();
                                })
                            })
                        </script>
                        <button type="button" id="Editar_guia_venta" class="btn_small btn_orange"><span>&nbsp;&nbsp;&nbsp;Editar&nbsp;&nbsp;&nbsp;</span></button> 
                        <button type="button" class="btn_small btn_orange"><span><a id="buscar_guia" href="<?php echo base_url(); ?>index.php/sales">Cancelar</a></span></button>
                        
                <?php
                        }
                    }
                } else {
                ?>
                    <button type="button" id="guardar_guia" class="btn_small btn_orange"><span>Guardar</span></button>
                    
                                <?php } ?>
                            <?php endif; ?>


        </div>
    </form>
    <span class="clear"></span>

    <div id="basic-modal-content">
        <script>
                                        $(document).ready(function() {
                                            $('#name').focus(function() {
                                                $('#boton_guardar_cliente').click();
                                              });
                                            $('#name').focus();                                                                       
                                            $('#boton_guardar_cliente').click(function(e) {
                                                var name = $('#name').val();
                                                var ruc = $('#ruc').val();
                                                var address = $('#address').val();
                                                var telephone = $('#telephone').val();
                                                var email = $('#email').val();                                                                                                                        
                                            $("#formAddClient").validate({
                                            rules: {
                                                name: {           //input name: fullName
                                                    required: true  //required boolean: true/false                                             
                                                },
                                                ruc: {           //input name: fullName
                                                    numeric: true  //required boolean: true/false                                             
                                                },
                                                telephone: {           //input name: fullName
                                                    numeric: true  //required boolean: true/false                                             
                                                },
                                                email: {            //input name: message                                       
                                                    email : true
                                                }
                                            },
                                            messages: {               //messages to appear on error
                                                name: {
                                                      required:"Debe ingresar su nombre"                                         
                                                      },
                                                ruc: {
                                                      numeric:"Debe ingresar sólo números"                                         
                                                      }, 
                                                telephone: {
                                                      numeric:"Debe ingresar sólo números"                                         
                                                      }, 
                                                email: {
                                                      email: "Introducir una dirección de correo válido"                                         
                                                      }
                                            }
                              
                           });
                           
                           
                                            });                                                                                        
                                        })
                                    </script> 
        <h3>Nuevo Cliente</h3>
        <form id="formAddClient" method="post" action="<?php echo base_url(); ?>index.php/clients/add" class="form_container left_label">
            <ul>
                <li>
                    <div class="form_grid_12">
                        <label class="field_title" for="rs">Razón Social <span class="req">*</span></label>
                        <div class="form_input">
                            <input type="text" id="name" name="name" value="<?php echo @field($client->name, set_value('name')); ?>" class="noEmpty" tabindex="20">
                            
                        </div>
                    </div>
                </li>
                <li>
                    <div class="form_grid_12">
                        <label class="field_title" for="ruc">RUC</label>
                        <div class="form_input">
                            <?php
                            $data = array(
                                'name' => 'ruc',
                                'id' => 'ruc',
                                'class' => 'onlyNumber',
                                'maxlength' => 11,
                                'value' => @field($client->ruc, set_value('ruc')),
                                'tabindex' => '21'
                            );
                            echo form_input($data);
                            ?>
                        </div>
                    </div>
                </li>
                <li>
                    <div class="form_grid_12">
                        <label class="field_title">Dirección</label>
                        <div class="form_input">
                            <?php
                            $data = array(
                                'name' => 'address',
                                'id' => 'address',
                                'value' => @field($client->address, set_value('address')),
                                'tabindex' => '22'
                            );
                            echo form_input($data);
                            ?>
                        </div>
                    </div>
                </li>
                <li>
                    <div class="form_grid_12">
                        <label class="field_title">Teléfono</label>
                        <div class="form_input">
                            <?php
                            $data = array(
                                'name' => 'telephone',
                                'id' => 'telephone',
                                'class' => 'onlyNumber',
                                'onkeypress' => 'return isNumberKey(event)',
                                'value' => @field($client->telephone, set_value('telephone')),
                                'tabindex' => '23'
                            );
                            echo form_input($data);
                            ?>
                        </div>
                    </div>
                </li>
                <li>
                    <div class="form_grid_12">
                        <label class="field_title">E-mail</label>
                        <div class="form_input">
                            <input type="text" name="email" id="email" class="email" value="<?php echo @field($client->email, set_value('email')); ?>" tabindex="24" placeholder="Email@4dominio.com">
<?php

/*$data = array(
    'name' => 'email',
    'id' => 'email',
    'class' => 'email',
    'type' => 'email',
    'value' => @field($client->email, set_value('email')),
    'tabindex' => '24',
    'placeholder' => 'EMAIL@dominio.com'
);
echo form_input($data);*/
?>
                        </div>
                    </div>
                </li>
                <li>
                    <div class="form_grid_12">
                        <script>
                           
                        </script>
                        <button type="submit" class="btn_small btn_orange" id="boton_guardar_cliente"><span>Guardar</span></button>
                    </div>
                </li>
            </ul>
        </form>
    </div>
    <div id="add-product-model">
    </div>
</div>

<table id="listProductBlank" class="clear">
    <tr id="rowListProductBlank" class="tr_even">
        <td class="elementList codeProduct"></td>
        <td class="elementList descriptionProduct"></td>
        <td class="elementList quantityBoxesProduct"></td>
        <td class="elementList quantityPackagesProduct"></td>
        <td class="elementList quantityUnitsProduct"></td>
        <td class="elementList priceProduct"></td>
        <td class="elementList inputProduct"><a href="#" class="action-icons c-Delete delProductList" original-title="Borrar">Delete</a></td>
    </tr>
</table>